<template>
  <div class="login">
    <LoginLeftView></LoginLeftView>

    <div class="right-wrap">
      <AuthTopBar></AuthTopBar>
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3 class="title">{{ $t('login.title') }}</h3>
          <p class="sub-title">{{ $t('login.subTitle') }}</p>
          <ElForm ref="formRef" :model="formData" :rules="rules" :key="formKey" @keyup.enter="handleSubmit"
            style="margin-top: 25px">
            <ElFormItem prop="account">
              <ElSelect v-model="formData.account" @change="setupAccount" class="account-select">
                <ElOption v-for="account in accounts" :key="account.key" :label="account.label" :value="account.key">
                  <span>{{ account.label }}</span>
                </ElOption>
              </ElSelect>
            </ElFormItem>
            <ElFormItem prop="username">
              <ElInput :placeholder="$t('login.placeholder.username')" v-model.trim="formData.username" />
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput :placeholder="$t('login.placeholder.password')" v-model.trim="formData.password" type="password"
                radius="8px" autocomplete="off" show-password />
            </ElFormItem>
            <div class="drag-verify">
              <div class="drag-verify-content" :class="{ error: !isPassing && isClickPass }">
                <ArtDragVerify ref="dragVerify" v-model:value="isPassing" :text="$t('login.sliderText')"
                  textColor="var(--art-gray-800)" :successText="$t('login.sliderSuccessText')"
                  :progressBarBg="getCssVar('--el-color-primary')" background="var(--art-gray-200)"
                  handlerBg="var(--art-main-bg-color)" />
              </div>
              <p class="error-text" :class="{ 'show-error-text': !isPassing && isClickPass }">{{
                $t('login.placeholder.slider')
              }}</p>
            </div>

            <div class="forget-password">
              <ElCheckbox v-model="formData.rememberPassword">{{
                $t('login.rememberPwd')
              }}</ElCheckbox>
              <RouterLink :to="{ name: 'ForgetPassword' }">{{ $t('login.forgetPwd') }}</RouterLink>
            </div>

            <div style="margin-top: 30px">
              <ElButton class="login-btn" type="primary" @click="handleSubmit" :loading="loading" v-ripple>
                {{ $t('login.btnText') }}
              </ElButton>
            </div>

            <div class="footer">
              <p>
                {{ $t('login.noAccount') }}
                <RouterLink :to="{ name: 'Register' }">{{ $t('login.register') }}</RouterLink>
              </p>
            </div>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AppConfig from '@/config'
import { useUserStore } from '@/store/modules/user'
import { getCssVar } from '@/utils/ui'
import { useI18n } from 'vue-i18n'
import { HttpError } from '@/utils/http/error'
import { fetchLogin, fetchGetUserInfo } from '@/api/auth'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'

defineOptions({ name: 'Login' })

const { t, locale } = useI18n()
const formKey = ref(0)

// 监听语言切换，重置表单
watch(locale, () => {
  formKey.value++
})

type AccountKey = 'super' | 'admin' | 'user'

export interface Account {
  key: AccountKey
  label: string
  username: string
  password: string
  roles: string[]
}

const accounts = computed<Account[]>(() => [
  {
    key: 'super',
    label: t('login.roles.super'),
    username: 'admin',
    password: 'Abc123',
    roles: ['R_SUPER']
  },
  {
    key: 'admin',
    label: t('login.roles.admin'),
    username: 'admin',
    password: 'Abc123',
    roles: ['R_ADMIN']
  },
  {
    key: 'user',
    label: t('login.roles.user'),
    username: 'User',
    password: '123456',
    roles: ['R_USER']
  }
])

const dragVerify = ref()

const userStore = useUserStore()
const router = useRouter()
const isPassing = ref(false)
const isClickPass = ref(false)

const systemName = AppConfig.systemInfo.name
const formRef = ref<FormInstance>()

const formData = reactive({
  account: '',
  username: '',
  password: '',
  rememberPassword: true
})

const rules = computed<FormRules>(() => ({
  username: [{ required: true, message: t('login.placeholder.username'), trigger: 'blur' }],
  password: [{ required: true, message: t('login.placeholder.password'), trigger: 'blur' }]
}))

const loading = ref(false)

onMounted(() => {
  setupAccount('super')
})

// 设置账号
const setupAccount = (key: AccountKey) => {
  const selectedAccount = accounts.value.find((account: Account) => account.key === key)
  formData.account = key
  formData.username = selectedAccount?.username ?? ''
  formData.password = selectedAccount?.password ?? ''
}

// 登录
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    // 拖拽验证
    if (!isPassing.value) {
      isClickPass.value = true
      return
    }

    loading.value = true

    // 登录请求
    const { username, password } = formData

    const { access_token: accessToken, refresh_token: refreshToken } = await fetchLogin({
      username,
      password
    })

    // 验证token
    if (!accessToken) {
      throw new Error('Login failed - no token received')
    }

    // 存储token和用户信息
    userStore.setToken(accessToken, refreshToken)
    const userInfo = await fetchGetUserInfo()
    userStore.setUserInfo(userInfo)
    userStore.setLoginStatus(true)

    // 登录成功处理
    showLoginSuccessNotice()
    router.push('/')
  } catch (error) {
    // 处理 HttpError
    if (error instanceof HttpError) {
      // console.log(error.code)
    } else {
      // 处理非 HttpError
      // ElMessage.error('登录失败，请稍后重试')
      console.error('[Login] Unexpected error:', error)
    }
  } finally {
    loading.value = false
    resetDragVerify()
  }
}

// 重置拖拽验证
const resetDragVerify = () => {
  dragVerify.value.reset()
}

// 登录成功提示
const showLoginSuccessNotice = () => {
  setTimeout(() => {
    ElNotification({
      title: t('login.success.title'),
      type: 'success',
      duration: 2500,
      zIndex: 10000,
      message: `${t('login.success.message')}, ${systemName}!`
    })
  }, 150)
}
</script>

<style lang="scss" scoped>
@use './index';
</style>